import * as Babel from '@babel/standalone';
import type { PluginObj } from '@babel/core';
import { ColumnRefInfo } from '../core/graph/ref/RefParser';
import _ from 'lodash';

/* eslint-disable prettier/prettier */
/* prettier-ignore */

const columnRefRegex = /^[A-Z]$/;

function ColumnRefParserPlugin(): PluginObj {
  return {
    name: 'ColumnRefParserPlugin',
    visitor: {
      Identifier(path, state: any) {
        const option: ColumnRefInfo = state?.opts ?? {
          columns: []
        };

        if (columnRefRegex.test(path.node.name) && !path.findParent(p => p.isCallExpression())) {
          option.columns.push(path.node.name);
        }
      },
    }
  }
}


export function parseColumnRefs(expression: string): ColumnRefInfo {
    
  const ret: ColumnRefInfo = {
    columns: []
  };

  Babel.transform(`const __value__ = (${expression})`, {
    filename: 'function1.ts',
    parserOpts: {
      plugins: ['typescript'],
    },
    plugins: [
      [
        ColumnRefParserPlugin,
        ret,
      ]
    ]
  });

  return {
    columns: _.uniq(ret.columns)
  };
}
